'use strict';
const Service = require('egg').Service;

class ArticleService extends Service {

  geTypeList(type_id = false) {
    const type = { 1: '国内新闻', 2: '国际新闻' };
    return type_id === false ? type : type[type_id];
  }

  // 获取文章分页列表
  async articlePageList(condition, page = 1, order = []) {
    const { pageSize } = this.config.common;
    const offset = (page - 1) * pageSize;
    if (!Object.keys(condition)) condition = { 1: 1 };
    if (!order.length) order = [['id', 'desc'], ['create_time', 'desc']];
    const results = this.ctx.model.Article.findAndCount({
      where: condition,
      order,
      limit: pageSize,
      offset,
      raw: true,
    });
    return results;
  }

  async setData(addData, condition = null) {
    const ctx = this.ctx;
    const title = addData.title;
    const desc = addData.desc || '';
    const type_id = parseInt(addData.type_id) || 0;
    const thumb = addData.thumb || '';
    const content = addData.content;
    const status = parseInt(addData.status) || 0;
    let data = { title, desc, type_id, thumb, content, status };
    let res = false;
    if (condition) {
      data.update_time = ctx.helper.date_to_time();
      res = await ctx.model.Article.update(data, { where: condition });
    } else {
      data.create_time = ctx.helper.date_to_time();
      res = await ctx.model.Article.create(data, { raw: true });
    }
    return !!res;
  }
}

module.exports = ArticleService;
